using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
using TDUnit.Common.TestData;

namespace TDUnit.TestDataParsers.XmlParser
{
    public class RowElementParser : ElementParserBase
    {
        private readonly ColumnElementParser colParser;

        public RowElementParser(ColumnElementParser colParser)
        {
            this.colParser = colParser;
        }

        public void Parse(IEnumerable<XElement> rowElements, Table table)
        {
            foreach (var rowElement in rowElements)
            {
                var row = ParseRowElement(rowElement, table);
                ParseColumnAttributesForRow(rowElement, row, table);
                colParser.Parse(rowElement.Elements(rowElement.GetDefaultNamespace() + "Column"), row);
            }
        }

        private static Row ParseRowElement(XElement rowElement, Table table)
        {
            var nameAttrib = rowElement.Attribute("Name");
            return table.AddRow(
                    new PrimaryKeyColumn(table.PrimaryKeyColumnName).WithIsAutoIdentity(table.IsPrimaryKeyAutoIdentity),
                    nameAttrib == null ? string.Empty : nameAttrib.Value);
        }

        private static void ParseColumnAttributesForRow(XElement rowElement, Row row, Table table)
        {
            var colAttributes = from c in rowElement.Attributes()
                                where c.Name != "Name" && c.Name != table.PrimaryKeyColumnName
                                select c;

            foreach (var attrib in colAttributes)
            {
                var colName = attrib.Name.LocalName;
                var colValue = attrib.Value;

                row.AddColumn(colName, colValue);
            }

            ParsePrimaryKeyFromRowAttribute(rowElement, row, table);
        }

        private static void ParsePrimaryKeyFromRowAttribute(XElement rowElement, Row row, Table table)
        {
            var pkCol = rowElement.Attribute(table.PrimaryKeyColumnName);
            if (pkCol != null)
                row.PrimaryKeyColumn.Value = pkCol.Value;
        }
    }
}